<template>
  <div class="lable-top">
    <folded-panel open>
      <el-form label-position="top" label-width="10px" size="mini">
        <el-row :gutter="10">
          <el-col :span="18">
            <el-form-item label="MEQL Query:">
              <el-input
                v-model="search.query"
                name="meql_query"
                placeholder="请输入 MEQL 查询表达式"
                spellcheck="false"
                type="textarea"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="5">
            <el-form-item v-permission="['super']" label="组织">
              <el-select
                v-model="search.org_id"
                :disabled="org_all"
                filterable
                @change="handleChangeOrg"
              >
                <el-option
                  v-for="(item, index) in company"
                  :key="index"
                  :label="item.name"
                  popper-class="w100"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="1">
            <el-form-item v-permission="['super']" label="全部">
              <el-checkbox v-model="org_all" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </folded-panel>
    <folded-panel class="mt10" open>
      <el-form label-position="top" size="small">
        <el-row :gutter="10">
          <el-col :span="4">
            <el-form-item label="终端">
              <el-select
                v-model="search.agent_id"
                :disabled="agent_all"
                filterable
              >
                <el-option
                  v-for="(item, index) in agentList"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                >
                  <span style="float: left">{{ item.name }}</span>
                  <span
                    :class="['status', item.online ? 'success' : 'fail']"
                    style="right: 0%; position: absolute; top: 50%; transform: translate(-100%, -50%)"
                  ></span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="全部">
              <el-checkbox v-model="agent_all" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="开始时间">
              <el-date-picker
                v-model="search.start_time"
                :picker-options="pickerOptions"
                placeholder="选择日期时间"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="结束时间">
              <el-date-picker
                v-model="search.end_time"
                :picker-options="pickerOptions"
                placeholder="选择日期时间"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label=" ">
              <el-button class="search" @click="handleNewSearch">
                <i class="el-icon-search"></i>
                搜寻
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </folded-panel>
    <el-button
      id="downlowd"
      class="mt10"
      size="small"
      @click="saveJson"
      @mouseenter="onMouseEnter()"
      @mouseleave="onmouseleave()"
    >
      <i v-show="showIcon">
        <img alt="" src="../../assets/icon/download.png"
      /></i>
      下载本页
    </el-button>
    <el-collapse class="mt10">
      <el-collapse-item v-for="item in jsonList" :key="item">
        <template slot="title">
          <div class="title">
            {{ item.Time + " " + item.SimpleName + " " + JSON.stringify(item) }}
          </div>
        </template>
        <json-viewer
          boxed
          copyable
          :expand-depth="5"
          expanded
          preview-mode
          sort
          :value="item"
        />
      </el-collapse-item>
    </el-collapse>
    <!-- 删除small -->
    <div class="mt10 el-row--flex is-justify-end">
      <el-pagination
        background
        :current-page="page"
        layout="total, prev, pager, next"
        :page-size="limit"
        :page-sizes="[100, 200, 300, 400]"
        :total="count"
        @current-change="handleCurrentChangePage"
      />
    </div>
  </div>
</template>

<script>
import FoldedPanel from "@/components/foldedPanel";
import JsonViewer from "vue-json-viewer";
import org_getall from "@/utils/mixin/org_getall";
import agent_name_list from "@/utils/mixin/agent_name_list";
import event from "@/api/event";
import { mapGetters } from "vuex";
export default {
  name: "EventHunter",
  components: { FoldedPanel, JsonViewer },
  mixins: [org_getall, agent_name_list],
  data: () => {
    return {
      pickerOptions: {
        shortcuts: [
          {
            text: "7 天前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            }
          },
          {
            text: "30 天前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", date);
            }
          },
          {
            text: "90 天前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", date);
            }
          }
        ]
      },
      showIcon: false,
      search: {
        query: "",
        org_id: undefined,
        agent_id: undefined,
        start_time: undefined,
        end_time: undefined
      },
      agent_all: false,
      org_all: false,
      page: 1,
      limit: 20,
      count: 0,
      jsonList: []
    };
  },
  computed: mapGetters(["UserInfo"]),
  watch: {
    showIcon: function(value) {
      if (value) {
        this.$nextTick(() => {
          this.showIcon = true;
          alert(this.showIcon);
        });
      } else {
        this.$nextTick(() => {
          this.showIcon = false;
        });
      }
    }
  },
  mounted() {
    this.init();
  },
  methods: {
    async init() {
      await this.loadingOrgGetall();
      await this.loadingAgent(this.search.org_id);

      if (this.$route.query.query) {
        this.search.query = this.$route.query.query;
        this.search.agent_id =
          parseInt(this.$route.query.agent_id) || undefined;
        this.search.start_time = this.$route.query.start_time || undefined;
        this.search.end_time = this.$route.query.end_time || undefined;
        await this.handleSearch();
      }
    },
    saveJson() {
      let data = this.jsonList.slice(0);
      let filename = new Date().getTime().toString() + ".json";
      if (!data.length) {
        return;
      }

      if (typeof data === "object") {
        data = JSON.stringify(data, undefined, 4);
      }
      var blob = new Blob([data], { type: "text/json" });
      var e = document.createEvent("MouseEvents");
      var a = document.createElement("a");
      a.download = filename;
      a.href = window.URL.createObjectURL(blob);
      a.dataset.downloadurl = ["text/json", a.download, a.href].join(":");
      e.initMouseEvent(
        "click",
        true,
        false,
        window,
        0,
        0,
        0,
        0,
        0,
        false,
        false,
        false,
        false,
        0,
        null
      );
      a.dispatchEvent(e);
    },
    handleChangeOrg(val) {
      this.search.agent_id = undefined;
      this.loadingAgent(val);
    },
    handleCurrentChangePage(val) {
      this.page = val;
      this.handleSearch();
    },
    handleSearch() {
      let queryData = Object.assign({}, this.search);
      if (this.agent_all) queryData.agent_id = 1;
      if (this.org_all) queryData.org_id = 1;
      let keys = Object.keys(queryData).filter(k => !queryData[k]);
      if (keys.length) {
        this.$message.warning("参数不完整");
        return;
      }
      if (this.agent_all) queryData.agent_id = 0;
      if (this.org_all) queryData.org_id = 0;
      return event
        .search({
          ...queryData,
          page: this.page,
          limit: this.limit
        })
        .then(res => {
          this.count = res.data.count;
          this.jsonList = res.data.result;
        });
    },
    handleNewSearch() {
      this.page = 1;
      this.handleSearch();
    },
    onMouseEnter() {
      alert(this.showIcon);
      this.showIcon = true;
    },
    onMouseLeave() {
      this.showIcon = false;
    }
  }
};
</script>

<style lang="scss" scoped>
.search {
  //padding: 0 30px;
  padding: 9px 50px;
  float: right;
  font-size: 14px;
}

::v-deep .el-collapse-item__header {
  .title {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
#downlowd {
  display: block;
  margin: 30px auto;
  background-color: #924141;
  color: aliceblue;
  font-size: 15px;
  font-weight: 500;
  vertical-align: middle;

  i img {
    width: 20px;
    height: 18px;
  }
}

#downlowd:hover {
  color: #924141;
  background-color: #fff;
  border: 1px solid #9e4e4e;
}

.status {
  width: 15px;
  height: 15px;
  border-radius: 100px;
}

.success {
  background-color: $--color-success;
}

.fail {
  background-color: $--color-danger;
}
</style>
